<?php


namespace app\common\server;

class ConfigServer
{
	public static function set($type, $name, $value)
	{
		$original = $value;
		$update_time = time();
		if (is_array($value)) {
			$value = json_encode($value, true);
		}
		$data = \think\Db::name("system_config")->where(["type" => $type, "name" => $name])->find();
		if (empty($data)) {
			\think\Db::name("system_config")->insert(["type" => $type, "name" => $name, "value" => $value]);
		} else {
			\think\Db::name("system_config")->where(["type" => $type, "name" => $name])->update(["value" => $value, "update_time" => $update_time]);
		}
		return $original;
	}
	public static function get($type, $name = "", $default_value = null)
	{
		if ($name) {
			$value = \think\Db::name("system_config")->where(["type" => $type, "name" => $name])->value("value", is_array($default_value) ? json_encode($default_value) : $default_value);
			$json = json_decode($value, true);
			if (json_last_error() === JSON_ERROR_NONE) {
				$value = $json;
			}
			return $value;
		}
		$data = \think\Db::name("system_config")->where(["type" => $type])->column("value", "name");
		foreach ($data as $k => $v) {
			$json = json_decode($v, true);
			if (json_last_error() === JSON_ERROR_NONE) {
				$data[$k] = $json;
			}
		}
		if ($data) {
			return $data;
		} else {
			return $default_value;
		}
	}
}